// @ts-nocheck
import React, { useState, useCallback } from 'react';
import { List, Spin, Alert, Button, Typography } from 'antd';
import { FileOutlined, ReloadOutlined } from '@ant-design/icons';
import { http } from '../../../../utils/httpClient';
import './index.less';

const { Text } = Typography;

// 文件数据结构
interface FileItem {
  name: string;
  size: number;
  modified: number;
  created: number;
  type: string;
  extension: string;
}

interface FileExplorerProps {
  onSelectFile: (fileContent: string, filePath: string) => void;
  fileList: FileItem[];
  loading: boolean;
  error: string | null;
  onRefresh: () => void;
}

const FileExplorer: React.FC<FileExplorerProps> = ({ 
  onSelectFile, 
  fileList, 
  loading, 
  error, 
  sessionId,
  onRefresh 
}) => {
  const [selectedFile, setSelectedFile] = useState<string | null>(null);
  const [fileLoading, setFileLoading] = useState(false);

  // 格式化文件大小
  const formatFileSize = useCallback((bytes: number) => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }, []);

  // 格式化时间
  const formatTime = useCallback((timestamp: number) => {
    return new Date(timestamp * 1000).toLocaleString('zh-CN');
  }, []);

  // 获取文件内容
  const fetchFileContent = useCallback(async (fileName: string) => {
    setFileLoading(true);
    try {
      const response = await http.post('/chatbiv3/sandbox', {
        source_id: '',
        session_id: sessionId || '',
        file_name: fileName
      });
      if (response && response.content) {
        const content = response.content || '文件内容不存在';
        onSelectFile(content, fileName);
        setSelectedFile(fileName);
      } else {
        onSelectFile('无法获取文件内容', fileName);
      }
    } catch (error) {
      console.error('获取文件内容失败:', error);
      onSelectFile('获取文件内容失败', fileName);
    } finally {
      setFileLoading(false);
    }
  }, [onSelectFile]);

  // 处理文件点击
  const handleFileClick = useCallback((file: FileItem) => {
    if (file.type === 'file') {
      fetchFileContent(file.name);
    }
  }, [fetchFileContent]);

  // 渲染文件列表项
  const renderFileItem = useCallback((file: FileItem) => {
    const isSelected = selectedFile === file.name;
    
    return (
      <List.Item
        key={file.name}
        className={`file-item ${isSelected ? 'selected' : ''}`}
        onClick={() => handleFileClick(file)}
        style={{
          cursor: file.type === 'file' ? 'pointer' : 'default',
          backgroundColor: isSelected ? '#e6f7ff' : 'transparent',
          padding: '12px 16px',
          borderRadius: '4px',
          margin: '2px 0'
        }}
      >
        <List.Item.Meta
          avatar={
            <FileOutlined 
              style={{ 
                color: file.type === 'file' ? '#1890ff' : '#999', 
                fontSize: '16px' 
              }} 
            />
          }
          title={
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Text strong={isSelected}>{file.name}</Text>
              <Text type="secondary" style={{ fontSize: '12px' }}>
                {formatFileSize(file.size)}
              </Text>
            </div>
          }
          description={
            <div style={{ fontSize: '12px', color: '#666' }}>
              <div>修改时间: {formatTime(file.modified)}</div>
              {file.extension && (
                <div>类型: {file.extension.toUpperCase()}</div>
              )}
            </div>
          }
        />
      </List.Item>
    );
  }, [selectedFile, handleFileClick, formatFileSize, formatTime]);

  return (
    <div className="file-explorer">
      {/* 错误提示和刷新按钮 */}
      {error && (
        <Alert
          message={error}
          type="error"
          showIcon
          style={{ marginBottom: 16 }}
          action={
            <Button size="small" icon={<ReloadOutlined />} onClick={onRefresh}>
              重试
            </Button>
          }
        />
      )}
      
      {/* 加载状态 */}
      {(loading || fileLoading) && (
        <div style={{ textAlign: 'center', padding: '16px 0' }}>
          <Spin size="small" />
          <span style={{ marginLeft: 8 }}>
            {loading ? '加载文件列表...' : '加载文件内容...'}
          </span>
        </div>
      )}
      
      {/* 文件列表 */}
      <div className="file-list">
        <List
          dataSource={fileList}
          renderItem={renderFileItem}
          style={{ maxHeight: '400px', overflowY: 'auto' }}
        />
        
        {/* 空状态提示 */}
        {/* {!loading && !error && fileList.length === 0 && (
          <div style={{ textAlign: 'center', padding: '32px 0', color: '#999' }}>
            暂无文件数据
          </div>
        )} */}
      </div>
    </div>
  );
};

export default React.memo(FileExplorer);
